<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="chooseHazardList"
    width="480px"
    okText="设置关联危险源"
    :body-style="{ height: '400px' }"
  >
    <div style="display: flex; flex-direction: row">
      <BasicTree
        height="310"
        style="width: 450px"
        :virtual="false"
        ref="treeRef"
        v-if="treeData"
        title="危险源清单列表"
        toolbar
        search
        :blockNode="true"
        :clickRowToExpand="false"
        :checkable="true"
        :treeData="treeData"
        :checkedKeys="checkedKeys"
      />
    </div>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted, computed, unref, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTree, TreeItem, TreeActionType } from '/@/components/Tree';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { Tag, Tooltip } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { Modal } from 'ant-design-vue';
  import { queryDangerDbTreeList } from '/@/api/ehs/templateHazard';
  import { setHazarditemsRelation, getHazardItemsRelation } from '/@/api/ehs/unitCategory';
  export default defineComponent({
    name: 'SetHasHazardList',
    components: {
      BasicTree,
      BasicModal,
    },
    setup(props, { emit }) {
      const treeData = ref([]);
      const checkedKeys = ref([]);
      // 当前操作的单元分类代码
      const uccd = ref('');
      const treeRef = ref<Nullable<TreeActionType>>(null);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const [register, { closeModal, changeLoading, changeOkLoading }] = useModalInner((data) => {
        treeData.value = [];
        checkedKeys.value = [];
        getTree().setSearchValue('');
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (data) {
            uccd.value = data.dataId;
            getHazardTree(data.hdbcd);
          }
        }
      });
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      function getTree() {
        const tree = unref(treeRef);
        if (!tree) {
          throw new Error('tree is null!');
        }
        return tree;
      }
      /**
       * 获取危险源清单树形结构数据
       */
      async function getHazardTree(hdbcd) {
        changeLoading(true);
        changeOkLoading(true);
        await queryDangerDbTreeList({ hdbcd: hdbcd, keytype: 0 }).then((res) => {
          treeData.value =
            res && res.length > 0
              ? JSON.parse(JSON.stringify(res).replace(/code/g, 'key').replace(/name/g, 'title'))
              : [];
          setTreeTitleHeight(treeData.value);
        });
        getHazardItemsRelation(uccd.value)
          .then((res) => {
            checkedKeys.value = res;
            changeLoading(false);
            changeOkLoading(false);
          })
          .catch((e) => {
            changeLoading(false);
            changeOkLoading(false);
            createMessage.error('获取关联危险源清单失败');
          });
        getTree().expandAll(true);
      }
      function chooseHazardList() {
        changeOkLoading(true);
        getTree().setSearchValue('');
        // 传递选择的导则库清单checkedKeys以及uccd
        setHazarditemsRelation({ uccd: uccd.value, hicds: getTree().getCheckedKeys() })
          .then((res) => {
            emit('success');
            createMessage.success('关联危险源清单成功');
            changeOkLoading(false);
            closeModal();
          })
          .catch((e) => {
            createMessage.error('关联危险源清单失败');
            changeOkLoading(false);
          });
      }

      function setTreeTitleHeight(tree) {
        tree.forEach((item) => {
          // let title = item.title.substring(0, 23) + '...';
          // item.title = h(Tooltip, { title: item.title }, title);
          let length = 0;
          // 根据字符串每个字符编码，判断当前字符是单字节还是双字节，然后统计字符串的字节长度。
          Array.from(item.title).map(function (char) {
            if (char.charCodeAt(0) > 255) {
              //字符编码大于255，说明是双字节字符
              length += 2;
            } else {
              length++;
            }
          });
          // 当前tree的宽度一行能容纳46字节长度,计算需要的行数,*26就是item的高度
          item.style = `height:${Math.ceil(length / 46) * 26}px;${
            item.ismajor && item.level == 3 ? 'color:red' : ''
          }`;
          // item.icon = item.ismajor && item.level == 3 ? 'ant-design:warning-outlined' : '';
          if (item.children && item.children.length > 0) {
            setTreeTitleHeight(item.children);
          }
        });
        return tree;
      }
      return {
        treeRef,
        register,
        chooseHazardList,
        checkedKeys,
        treeData,
        displayModuleTitle,
      };
    },
  });
</script>

<style scoped>
  :deep(.ant-tree-node-content-wrapper) {
    height: 100%;
  }
</style>
